<?php
	session_start();
?>
<html>
	<head>
		<title>MNWiki - Зураг бүхэн нартай байг!</title>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<link rel="stylesheet" type="text/css" href="css/styles.css" />
		<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
		<script type="text/javascript">
		
			var mn_title;
			var mn_h_id;
			var mn_recent_page = 0;
			
			$(document).ready(function() {
				var hash = $.trim(document.location.hash);
				var len = hash.length;
				if (len > 0) {	
					var title = hash.substring(1,len);
					fetch(title);
				} else {
					fetch("Нүүр хуудас");
					
				}
				mn_recent();
			});
			
			function mn_recent() {
				$.ajax({
					type: "POST",
					url: 'ajax.post.php',
					data: 'func=recent&lower=' + mn_recent_page + '&higher=' + (mn_recent_page+20),
					success: function(data) {
						mn_recent_page = mn_recent_page+20;
						recents = jQuery.parseJSON(data);
						if (recents.length != 0) {
							var results = "<ul>";
							for (var i=0; i < recents.length; i++) {
								results += "<li>";
								results += recents[i].date + " - ";
								results += "<a href='javascript:;' onclick='jump(\"" + recents[i].title + "\");'>" + recents[i].title + "</a> - ";
								results += "<a href='javascript:;' onclick='jump(\"Гишүүн:" + recents[i].user + "\");'>" + recents[i].user + "</a> өөрчиллөө.";
								results += "</li>";
							}
							results += "</ul>";
							$("#mn_recent").html(results);
						}					
					}
				});
			}
			
			function inform(msg) {
				$("#mn_info").hide("fast");
				$("#mn_info").html("<img src='images/warning.png' width='20' align='absmiddle'> " + msg);
				$("#mn_info").show("slow");
			}
			
			function reset() {
				$("#mn_post_new_content").val('');
				$("#mn_post_edit_title").text('');
				$("#mn_post_edit_content").val('');
				$("#mn_post_title").html('');							
				$("#mn_post_content").html('');
				$("#mn_children_dir").html('');
				$("#mn_children").html('');
				$("#mn_info").hide();
				$("#mn_history_timeline").html('');
				$("#mn_history_view").html('');
				$("#mn_history").hide();
				$("#mn_post_new").hide();
				$("#mn_post_edit").hide();
				$("#mn_discuss").html('');
				$("#mn_recent").html('');
				mn_recent_page = 0;
                                mn_recent();
				// $("#mn_search_results").html('');
			}
			
			function mn_children(title) {
				
				var title_a = title.split("/");
				var title_a_s = title_a.length;
				
				// var parentdir_i = title.lastIndexOf("/");
				// var parentdir = title.substring(0, parentdir_i);
				
				$("#mn_children_dir").html(title + "/");
				
				$.ajax({
					type: "POST",
					url: 'ajax.post.php',
					data: 'func=children&title=' + title.replace(/&/g, "%26"),
					success: function(data) {
						if (data == "NONE") {
							return;
						} else { 
							children = jQuery.parseJSON(data);
							var results = "<ul>";
							for (var i=0; i < children.length; i++) {
								results += "<li><a href='javascript:;' onclick='jump(\"" + children[i].title + "\");'>" + children[i].title.split("/")[title_a_s] + "</a></li>";
							}
							results += "</ul>";
							$("#mn_children").html(results);
						}
					}
				});
			}
                        
                        function mn_unjsonify_content(input) {                                
                                // var input_t1 = input.replace(/<br>/g, "\n")
				var input_t2 = input.replace(/&#34;/g, "\"");
                                var input_t3 = input_t2.replace(/&#92;/g, "\\");
                                var output = input_t3.replace(/&#39;/g, "\'");
				return output;
                        }
                        
                        function mn_unjsonify(input) {                                
                                var input_t1 = input.replace(/<br>/g, "\n")
				var input_t2 = input_t1.replace(/&#34;/g, "\"");
                                var input_t3 = input_t2.replace(/&#92;/g, "\\");
                                var output = input_t3.replace(/&#39;/g, "\'");
				return output;
                        }
			
			function fetch(title) {							
				
				$("#mn_search").val(title);
				
				var expl = title.split("/");
				var expl_s = expl.length;
				
				if (expl[expl_s-2] != null) {
					var parentdir_i = title.lastIndexOf("/");
					var parentdir = title.substring(0, parentdir_i);
					$("#mn_up").html("<a href='javascript:;' onclick='jump(\"" + parentdir + "\");'>^ " + expl[expl_s-2] + "</a>");
				} else {
					$("#mn_up").html("");
				}
				
				$.ajax({
					type: "POST",
					url: 'ajax.post.php',
					data: 'func=fetch&title=' + title.replace(/&/g, "%26"),
					success: function(data) {
						if (data == "NONE") {
							reset();
							$("#mn_edit_link").css("display", "none");
							if (title.substring(0,7) == "Гишүүн:") {
								var user_s = title.length;
								var user = title.substring(7, user_s);
								inform("<strong>" + user + "</strong> хэрэглэгч байхгүй байна.");
								return;
							}
							if (title.substring(0,6) == "Зураг:") {
								var img_s = title.length;
								var img = title.substring(6, img_s);
								inform("<strong>" + img + "</strong> нэртэй зураг байхгүй байна.");
								return;
							}
							if (title.substring(0,12) == "Хэлэлцүүлэг:") {
								var discuss_s = title.length;
								var discuss = title.substring(12, discuss_s);
								inform("<strong>" + discuss + "</strong> гарчигтай нийтлэл байхгүй байна.");
								return;
							}
							if (title.substring(0,21) == "Гишүүний хэлэлцүүлэг:") {
								var discuss_s = title.length;
								var discuss = title.substring(12, discuss_s);
								inform("<strong>" + discuss + "</strong> хэрэглэгч байхгүй байна.");
								return;
							}
							inform("<strong>" + title + "</strong> гарчигтай нийтлэл байхгүй байна. <a href='javascript:;' onclick='$(\"#mn_post_new\").show(\"slow\");'>Энд</a> дарж үүсгэнэ үү!");
							$("#mn_post_new_title").text(title);
							
						} else { 
							reset();
							post = jQuery.parseJSON(data);
							$("#mn_post_title").html(post.title);
							$("#mn_post_content").html(mn_unjsonify_content(post.content));
							$("#mn_post_edit_id").val(post.id);
							$("#mn_post_edit_title").text(post.title);
							$("#mn_post_edit_content").val(mn_unjsonify(post.source));
							$("#mn_edit_link").css("display", "block");
							mn_children(title);
							mn_title = title;
							
							if (title.substring(0,12) == "Хэлэлцүүлэг:" || title.substring(0,21) == "Гишүүний хэлэлцүүлэг:") {
								var user_t_s = title.length;
								if (title.substring(0,12) == "Хэлэлцүүлэг:") {
									var t_title = title.substring(12,user_t_s);
									$("#mn_discuss").html("<a href='javascript:;' onclick='jump(\"" + t_title + "\");'>" + t_title + "</a>");
								}
								if (title.substring(0,21) == "Гишүүний хэлэлцүүлэг:") {
									var t_title = title.substring(21,user_t_s);
									$("#mn_discuss").html("<a href='javascript:;' onclick='jump(\"Гишүүн:" + t_title + "\");'>Гишүүн:" + t_title + "</a>");
								}
							} else {								
								if (title.substring(0,7) == "Гишүүн:") {
									var user_t_s = title.length;
									$("#mn_discuss").html("<a href='javascript:;' onclick='jump(\"Гишүүний хэлэлцүүлэг:" + title.substring(7,user_t_s) + "\");'>Гишүүний хэлэлцүүлэг</a>");
								} else {
									$("#mn_discuss").html("<a href='javascript:;' onclick='jump(\"Хэлэлцүүлэг:" + title + "\");'>Хэлэлцүүлэг</a>");
								}
							}
						}
					}
				});
			}
			
			function mn_search(title) {							
				$.ajax({
					type: "POST",
					url: 'ajax.post.php',
					data: 'func=search&title=' + title.replace(/&/g, "%26"),
					success: function(data) {
						if (data == "NONE") {
							return;
						} else { 
							var posts = jQuery.parseJSON(data);
							var results = "<ul>";
							for (var i=0; i < posts.length; i++) {
								results += "<li><a href='javascript:;' onclick='jump(\"" + posts[i].title + "\");'>" + posts[i].title + "</a></li>";
							}
							results += "</ul>";
							$("#mn_search_results").html(results);
						}
					}
				});
			}
			
			function mn_escape(input) {
				var input_t1 = input.replace(/\n/g, "<br>");
				var output = input_t1.replace(/&/g, "%26");
				// var output = input_t2.replace(/\n/g, "&#92;n");
				return output;
			}
			
			function create() {
				var title = $.trim($("#mn_post_new_title").text());
				var content_t = $.trim($("#mn_post_new_content").val());
				var userid = 1;
				
				if (title == "" || content_t == "") {
					inform("Гарчиг болон агуулга хоосон байж болохгүй!");
					return;
				}
				
				var content = mn_escape(content_t);
				
				$.ajax({
					type: "POST",
					url: 'ajax.post.php',
					data: 'func=create&title=' + title.replace(/&/g, "%26") + '&content=' + content,
					success: function(data) {
						location.reload();
					}
				});
			}
			
			function edit() {
				var id = $.trim($("#mn_post_edit_id").val());
				var title = $.trim($("#mn_post_edit_title").text());
				var content_t = $.trim($("#mn_post_edit_content").val());
				
				if (title == "" || content_t == "") {
					inform("Агуулга хоосон байж болохгүй!");
					return;
				}
				
				var content = mn_escape(content_t);
				
				$.ajax({
					type: "POST",
					url: 'ajax.post.php',
					data: 'func=edit&title=' + title.replace(/&/g, "%26") + '&content=' + content,
					success: function(data) {
						location.reload();
					}
				});
			}
			
			function mn_undo() {
				$.ajax({
					type: "POST",
					url: 'ajax.post.php',
					data: 'func=undo&title=' + mn_title.replace(/&/g, "%26") + '&id=' + mn_h_id,
					success: function(data) {
						location.reload();
					}
				});
			}
			
			function read() {
				var title = $.trim($('#mn_search').val());
				if (title != '') {
					document.location = '#' + title;
					fetch(title);
					mn_search(title);
				}
			}
			
			function jump(title) {
				if (title != '') {
					document.location = '#' + title;
					fetch(title);
				}
			}
			
			function utilize(type, elem) {
				var textarea = document.getElementById(elem); 
				var len = textarea.value.length; 
				var start = textarea.selectionStart; 
				var end = textarea.selectionEnd; 
				var sel = textarea.value.substring(start, end);
				var replace = "";
				switch(type) {
					case "link":
						replace = '[[' + sel + ']]';
						break;
					case "bold":
						replace = '<strong>' + sel + '</strong>';
						break;
					case "italic":
						replace = '<em>' + sel + '</em>';
						break;
					case "underline":
						replace = '<u>' + sel + '</u>';
						break;
					case "h2":
						replace = '<h2>' + sel + '</h2>';
						break;
					default:
						break;
				} 
				
				textarea.value = textarea.value.substring(0,start) + replace + 
					textarea.value.substring(end,len);
			}
			
			function mn_history() {
				$.ajax({
					type: "POST",
					url: 'ajax.post.php',
					data: 'func=history&title=' + mn_title.replace(/&/g, "%26"),
					success: function(data) {
						var hist = jQuery.parseJSON(data);
						var res_h = "<ul>";
						for (var i=0; i<hist.length; i++) {
							h = hist[i];
							res_h += "<li><a href='javascript:;' onclick='history_view(\"" + h.id + "\");'>" + h.date + "</a> - <a href='javascript:;' onclick='jump(\"Гишүүн:" + h.user + "\");'>" + h.user + "</a> (хэмжээ: " + h.size + ")</li>";
						}
						res_h += "</ul>";
						$("#mn_history_timeline").html(res_h);
						$("#mn_history").show("slow");
					}
				});
			}
			
			function history_view(id) {
				mn_h_id = id;
				$.ajax({
					type: "POST",
					url: 'ajax.post.php',
					data: 'func=history_view&id=' + id,
					success: function(data) {
						post = jQuery.parseJSON(data);
						$("#mn_history_view_date").html(post.date);
						$("#mn_history_view").html(post.content);
						$("#mn_history_view_wrapper").show();
					}
				});
			}
			
			function mn_login() {
				var user = $.trim($("#mn_user").val());
				var password = $.trim($("#mn_password").val());
				if (user == "" || password == "") {
					inform("Гишүүний нэр, нууц үг оруулна уу!");
					return;
				}
				$.ajax({
					type: "POST",
					url: 'ajax.user.php',
					data: 'func=login&user=' + user.replace(/&/g, "%26") + '&password=' + password.replace(/&/g, "%26"),
					success: function(data) {
						if (data == "SUCCESS") {
							location.reload();
						} else {
							inform("Гишүүний нэр эсвэл нууц үг буруу байна!");
							return;
						}
					}
				});
			}
			
			function mn_logout() {
				$.ajax({
					type: "POST",
					url: 'ajax.user.php',
					data: 'func=logout',
					success: function(data) {
						location.reload();
					}
				});
			}
			
			function mn_register() {
				var user = $.trim($("#mn_reg_user").val());
				var password = $.trim($("#mn_reg_password").val());
				var password2 = $.trim($("#mn_reg_password_again").val());
				var email = $.trim($("#mn_reg_email").val());
				if (user == "" || password == "" || password2 == "" || email == "") {
					inform("Бүх мэдээллийг оруулна уу!");
					return;
				}
				if (password != password2) {
					inform("Нууц үг болон Нууц үг (Ахиад) адилхан биш байна!");
					return;
				}
				$.ajax({
					type: "POST",
					url: 'ajax.user.php',
					data: 'func=register&user=' + user.replace(/&/g, "%26") + '&password=' + password.replace(/&/g, "%26") + '&email=' + email,
					success: function(data) {
						if (data == "DUPLICATE") {
							inform("Энэ хэрэглэгчийн нэр эсвэл электрон шуудангаар өмнө бүртгэл хийгдсэн байна! Та өөрийг сонгоно уу!");
							return;
						}
						inform("Бүртгэл амжилттай боллоо! Одоо нэвтэрч болно!");
						$('#mn_register').hide('fast');
						$('#mn_login').show('slow');
						return;
					}
				});
			}
		</script>
	</head>
	<body>
		<div id="mn_nav">
			<div class="mn_wrapper">
				<div class="mn_box mn_shine">
					<h2>Хайлтын хариу</h2>
                                        <div id="mn_search_results" >
                                                
                                        </div>
				</div>
				<div class="mn_box">
					<ul>
						<li><a href="javascript:;" onclick="jump('Нүүр хуудас');">Нүүр хуудас</a></li>
						<li><a href="javascript:;" onclick="jump('МНВики');">Бидний тухай</a></li>
					</ul>
				</div>
				<?php
					if ($_SESSION["mnwiki_user"] == NULL) {
				?>
					<div id="mn_login" class="mn_box">
						<table width="100%">
							<tr>
								<td>Гишүүний нэр</td>
								<td>
									<input id="mn_user" maxlength="30" onkeypress="if (event.keyCode == 13) { mn_login(); }" />
								</td>
							</tr>
							<tr>
								<td>Нууц үг</td>
								<td><input id="mn_password" type="password" maxlength="30" onkeypress="if (event.keyCode == 13) { mn_login(); }" /></td>
							</tr>
							<tr>
								<td>&nbsp;</td>
								<td><button onclick="mn_login();">Нэвтэр</button> <a href="javascript:;" onclick="$('#mn_login').hide('fast');$('#mn_register').show('slow');">Бүртгүүл</a></td>
							</tr>
						</table>
					</div>
					<div id="mn_register" class="mn_box" style="display: none;">
						<table width="100%">
							<tr>
								<td>Гишүүний нэр</td>
								<td>
									<input id="mn_reg_user" maxlength="30" />
								</td>
							</tr>
							<tr>
								<td>Нууц үг</td>
								<td><input id="mn_reg_password" type="password" maxlength="30" /></td>
							</tr>
							<tr>
								<td>Нууц үг (Ахиад)</td>
								<td><input id="mn_reg_password_again" type="password" maxlength="30" /></td>
							</tr>
							<tr>
								<td>Электрон шуудан</td>
								<td><input id="mn_reg_email" maxlength="50" /></td>
							</tr>
							<tr>
								<td>&nbsp;</td>
								<td><button onclick="mn_register();">Бүртгүүл</button> <a href="javascript:;" onclick="$('#mn_register').hide('fast');$('#mn_login').show('slow');">Нэвтэр</a></td>
							</tr>
						</table>
					</div>
				<?php
					} else {
				?>
					<div class="mn_box">
						Сайн уу, <a href="javascript:;" onclick="jump('Гишүүн:<?php print $_SESSION['mnwiki_user']; ?>');"><?php print htmlspecialchars($_SESSION['mnwiki_user']); ?></a>!
						<ul>
							<li><a href="javascript:;" onclick="mn_logout();">Гарах</a></li>
						</ul>
					</div>
				<?php
					}
				?>
			</div>
		</div>
		<div id="mn_main">
			<div class="mn_box mn_shine">
				<table width="100%">
					<tr>
						<td width="33%">
							<span id="mn_back" style="">
								<a href="javascript:;" onclick="history.go(-1); setTimeout('location.reload();', 500);">&lt; Буц</a>
							</span> 
						</td>
						<td width="33%">
							<span id="mn_up">
								
							</span>
						</td>
						<td width="33%" align="right">
							<span id="mn_forward">
								<a href="javascript:;" onclick="history.go(1); setTimeout('location.reload();', 500);">Урагшил &gt;</a>
							</span>
						</td>
					</tr>
				</table>
			</div>
                        <div class="mn_box mn_shine">
				<table width="100%">
					<tr>
						<td>
							<input id="mn_search" onkeypress="if (event.keyCode == 13) { read(); }" style="width: 100%;" class="mn_search_box" />
						</td>
					</tr>
					<tr>
						<td>
							<button onclick="read();">Хай</button>
						</td>
					</tr>
				</table>				
			</div>
			<div class="mn_wrapper mn_box">
				<div id="mn_info" class="mn_notif" style="display: none;"></div>
				<div id="mn_history" class="mn_editor" style="display: none;">
					<button onclick="$('#mn_history').hide('fast');">Хаа</button>
					<div id="mn_history_timeline"></div>
					<div id="mn_history_view_wrapper" style="display: none;">
						<hr />
						<h1 id="mn_history_view_date" style="background-color: #f0f0f0;"></h1>
						<?php
							if ($_SESSION["mnwiki_user"] == NULL) {
						?>
							<div class="mn_notif">Хуучин хувилбарлуу буцаахын тулд системд нэвтэрсэн байх ёстой!</div>
						<?php } else { ?>
							<button onclick="mn_undo();">Энэ хувилбарлуу буцаа</button>
							<hr />
						<?php } ?>
						<div id="mn_history_view"></div>
					</div>
				</div>
				<div id="mn_post_new" class="mn_editor" style="display: none;">
					<?php
						if ($_SESSION["mnwiki_user"] == NULL) {
					?>
						<div class="mn_notif">Шинэ нийтлэл үүсгэхийн тулд системд нэвтэрсэн байх ёстой!</div>
					<?php } else { ?>
						<table width="100%">
							<tr>
								<td>Гарчиг</td>
								<td>
									<span id="mn_post_new_title"></span>
								</td>
							</tr>
							<tr>
								<td valign="top">Агуулга</td>
								<td>
									<div>
										<button onclick="utilize('bold', 'mn_post_new_content');" title="зузаан"><strong>зузаан</strong></button> 
										<button onclick="utilize('italic', 'mn_post_new_content');" title="налуу"><em>налуу</em></button> 
										<button onclick="utilize('underline', 'mn_post_new_content');" title="зураастай"><u>зураастай</u></button> 
										<button onclick="utilize('h2', 'mn_post_new_content');" title="толгой"><h2>толгой</h2></button> 
										<button onclick="utilize('link', 'mn_post_new_content');" title="холбоос"><a>холбоос</a></button> 
									</div>
									<textarea id="mn_post_new_content"></textarea>
								</td>
							</tr>
							<tr>
								<td>&nbsp;</td>
								<td>
									<button onclick="create();">Нэм</button> 
									<button onclick="$('#mn_post_new').hide('slow');">Боль</button>
								</td>
							</tr>
						</table>
					<?php } ?>
				</div>
				<div id="mn_post_edit" class="mn_editor" style="display: none;">
					<?php
						if ($_SESSION["mnwiki_user"] == NULL) {
					?>
						<div class="mn_notif">Нийтлэл өөрчлөхийн тулд системд нэвтэрсэн байх ёстой!</div>
					<?php } else { ?>
						<table width="100%">
							<tr>
								<td>Гарчиг</td>
								<td>
									<span id="mn_post_edit_title"></span> 
									<input id="mn_post_edit_id" type="hidden" />
								</td>
							</tr>
							<tr>
								<td valign="top">Агуулга</td>
								<td>
									<div>
										<button onclick="utilize('bold', 'mn_post_edit_content');" title="зузаан"><strong>зузаан</strong></button> 
										<button onclick="utilize('italic', 'mn_post_edit_content');" title="налуу"><em>налуу</em></button> 
										<button onclick="utilize('underline', 'mn_post_edit_content');" title="зураастай"><u>зураастай</u></button> 
										<button onclick="utilize('h2', 'mn_post_edit_content');" title="толгой"><h2>толгой</h2></button> 
										<button onclick="utilize('link', 'mn_post_edit_content');" title="холбоос"><a>холбоос</a></button> 
									</div>
									<textarea id="mn_post_edit_content"></textarea>
								</td>
							</tr>
							<tr>
								<td>&nbsp;</td>
								<td>
									<button onclick="edit();">Өөрчил</button> 
									<button onclick="$('#mn_post_edit').hide('slow');">Боль</button>
								</td>
							</tr>
						</table>
					<?php } ?>
				</div>
				<div id="mn_edit_link">
					<a href="javascript:;" onclick="$('#mn_post_edit').show('slow');">Өөрчил</a> | 
					<a href="javascript:;" onclick="mn_history();">Өөрчилсөн түүх</a> | 
					<strong id="mn_discuss"></strong>
				</div>			
				<h1 id="mn_post_title">
			
				</h1>
				<div id="mn_post_content">
			
				</div>
			</div>
			<div class="mn_wrapper mn_box">
				<h2>Хавтас</h2>
                                <div id="mn_children_dir" style="margin-bottom: 5px; padding: 3px; background-color: #f0f0f0;">
					
				</div>
				<div id="mn_children">
					
				</div>
			</div>
			<div class="mn_wrapper mn_box">
				<h2>Шинэ өөрчлөлтүүд</h2>
                                <div id="mn_recent"></div>
                                <button onclick="mn_recent();">Илүү</button>
			</div>
		</div>
	</body>
</html>
